package com.eshop.inventory.service.impl;

import com.eshop.inventory.mapper.ProductInventoryMapper;
import com.eshop.inventory.model.ProductInventory;
import com.eshop.inventory.service.ProductInventoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author: Xukai
 * @description: 商品库存service接口实现类
 * @createDate: 2018/7/23 14:00
 * @modified By:
 */
@Service
public class ProductInventoryServiceImpl implements ProductInventoryService {

    @Autowired
    private ProductInventoryMapper productInventoryMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void removeProductInventoryCache(ProductInventory productInventory) {
        String key = "product:inventory:" + productInventory.getProductId();
        redisTemplate.opsForValue().getOperations().delete(key);
    }

    @Override
    public void setProductInventoryCache(ProductInventory productInventory) {
        String key = "product:inventory:" + productInventory.getProductId();
        redisTemplate.opsForValue().set(key, String.valueOf(productInventory.getInventoryCnt()));
    }

    @Override
    public void updateProductInventory(ProductInventory productInventory) {
        productInventoryMapper.updateProductInventory(productInventory);
    }

    @Override
    public ProductInventory findProductInventory(Integer productId) {
        return productInventoryMapper.findProductInventory(productId);
    }

    @Override
    public ProductInventory getProductInventoryCache(Integer productId) {
        String key = "product:inventory:" + productId;
        String inventoryCntStr = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(inventoryCntStr)) {
            try {
                return new ProductInventory(productId, Long.valueOf(inventoryCntStr));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
